package calao;

import java.util.Vector;

import calao.client.WorkspaceService;
import calao.client.MissingPermissionException;
import calao.client.WorkspaceInfo;
import calao.storage.Record;
import calao.storage.Storage;
import calao.util.Cursor;

public class WorkspaceServiceImpl 
extends DesktopServiceImpl 
implements WorkspaceService 
{

	public WorkspaceInfo[] listWorkspaces()
	{
		Storage db = ws.server.storage;
		Cursor<Record> cursor = db.list(Workspace.TABLE);
		Vector<WorkspaceInfo> result = new Vector<WorkspaceInfo>();
		while (cursor.next()) {
			Record record = cursor.get();
			String path = record.get(Workspace.PATH);
			int wsid = record.get(Workspace.ID);
			if (path.startsWith(ws.getPath()) && wsid!=ws.getId()) {
				Integer parentWSID = record.get(Workspace.PARENT_ID);
				WorkspaceInfo info = new WorkspaceInfo(wsid,
						parentWSID!=null? parentWSID : -1, path);
				result.add(info);
			}
		}
		cursor.close();
		return result.toArray(new WorkspaceInfo[result.size()]);
	}

	public boolean isApplicationAvailable(String name) 
	{
		// TODO check if application is available
		return true;
	}

	static WorkspaceInfo toInfo(Workspace ws)
	{
		int pwsid = ws.parent!=null? ws.parent.id : -1; 
		WorkspaceInfo info = new WorkspaceInfo(ws.id, pwsid, ws.getPath());
		info.setProperties(ws.properties.map);
		return info;
	}
	
	public WorkspaceInfo detailWorkspace(int wsid) 
	throws MissingPermissionException 
	{
		// TODO check permission
		Record wsRec = ws.server.storage.fetch(Workspace.TABLE, wsid);
		if (wsRec==null) return null;
		Integer pwsid = wsRec.get(Workspace.PARENT_ID); 
		String path = wsRec.get(Workspace.PATH);
		WorkspaceInfo info = new WorkspaceInfo(wsid, pwsid!=null? pwsid : -1, path); 
		info.setProperties(wsRec.get(Workspace.PROPERTIES));
		return info;
	}

	public WorkspaceInfo createWorkspace(String path) 
	throws MissingPermissionException {
		// TODO check permission
		int wsid = ws.createWorkspace(path);
		int parentWSID = ws.getWorkspaceId(Workspace.getParentPath(path));
		return new WorkspaceInfo(wsid, parentWSID, path);
	}

	public void deleteWorkspace(int wsid)
	throws MissingPermissionException 
	{
		ws.deleteWorkspace(wsid);
	}
		
}
